import { gifler } from "gifler";

import "ol/ol.css";
import * as control from "ol/control";
import { Feature, Map, View } from "ol/index";
import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import { Point } from "ol/geom";

import target_gif from "./img/01.gif";
import target_gif2 from "./img/02.gif";
import { Icon, Style } from "ol/style";
let map;
//两个gif图标
const targetStyles = [
  new Style({
    image: new Icon({
      src: target_gif,
      scale: 0.5,
    }),
  }),
  new Style({
    image: new Icon({
      src: target_gif2,
      scale: 0.5,
      color: "#FFF",
    }),
  }),
];

var gifStyles = {}; //用于存放gifStyles
//预先创建gif
function createGifStyle(name, gifImage, scaleSize) {
  if (gifStyles[name] == null) {
    console.log("正在预创建gif动态图样式：" + name);
    gifler(gifImage).frames(
      document.createElement("canvas"),
      function (ctx, frame) {
        gifStyles[name] = new Style({
          image: new Icon({
            img: ctx.canvas,
            imgSize: [frame.width, frame.height],
            opacity: 1,
            size: scaleSize,
          }),
        });
        if (scaleSize == null) {
          scaleSize = [frame.width, frame.height];
        }
        ctx.clearRect(0, 0, scaleSize[0], scaleSize[1]);
        ctx.drawImage(
          frame.buffer,
          0,
          0,
          frame.width,
          frame.height,
          0,
          0,
          scaleSize[0],
          scaleSize[1]
        );
        map.render();
      },
      true
    );
  }
}
//根据样式表批量创建gif样式
function createGifStyles(iconStyles) {
  for (let i in iconStyles) {
    let iconStyle = iconStyles[i];
    if (iconStyle.gif != null) {
      createGifStyle(iconStyle.name, iconStyle.gif, iconStyle.size);
    }
  }
}
//获取gif动态图样式
function getGifStyle(name) {
  return gifStyles[name];
}
export const initMap = (mapDon) => {
  //创建地图
  map = new Map({
    target: mapDon,
    controls: control.defaults({
      attribution: false,
      zoom: true,
      rotate: true,
    }),
    view: new View({
      center: [119, 32],
      maxZoom: 21,
      zoom: 8,
      minZoom: 7,
      projection: "EPSG:4326",
    }),
  });
  var vectorLayer = new VectorLayer({
    zIndex: 1,
    source: new VectorSource({
      features: [],
    }),
  });
  map.addLayer(vectorLayer);
  //批量创建gif图片样式
  createGifStyles(targetStyles);
  let feature = new Feature({
    id: 1,
    name: "测试",
    geometry: new Point([119, 33]),
  });
  //这样gif就可以像正常的图片style一样被设置
  feature.setStyle(getGifStyle("target"));
  //把图标要素添加到图层
  vectorLayer.getSource().addFeature(feature);
};
